"use strict";
$jq.namespace('PeopleMedia');
$jq.namespace('PeopleMedia.Types');

PeopleMedia.Diagnostics = function () {
    var _exceptionHandler = null;

    return {
        registerExceptionHandler: function (exceptionHandler) {
            _exceptionHandler = exceptionHandler;
        },

        handleException: function (exception, detail) {
            if (_exceptionHandler != null) {
                _exceptionHandler(exception, detail);
            } else {
                throw exception;
            }
        }
    };
} ();

PeopleMedia.Delegate = function() {
    var _handlers = [];
    
    return {
        Oid: "PeopleMedia.Delegate",
        add: function (handler) {
            try {
                if (handler && Object.prototype.toString.call(handler) === '[object Function]') {
                    _handlers.push(handler);
                }
            }
            catch (ex) {
                PeopleMedia.Diagnostics.handleException(ex, { oid: this.Oid, method: "add" });
            }
        },
        
        fire: function () {
            try {
                for (var i = 0; i < _handlers.length; i++) {
                    try {
                        _handlers[i](arguments);
                    }
                    catch (ex) {
                        PeopleMedia.Diagnostics.handleException(ex, { oid: this.Oid, method: "fire (handler)", i:i });
                    }
                }
                _handlers = [];
            }
            catch (ex) {
                PeopleMedia.Diagnostics.handleException(ex, { oid: this.Oid, method: "fire" });
            }
        },
        
        fireAndPreserve: function () {
            try {
                for (var i = 0; i < _handlers.length; i++) {
                    try {
                        _handlers[i](arguments);
                    }
                    catch (ex) {
                        PeopleMedia.Diagnostics.handleException(ex, { oid: this.Oid, method: "fire (handler)", i: i });
                    }
                }
            }
            catch (ex) {
                PeopleMedia.Diagnostics.handleException(ex, { oid: this.Oid, method: "fireAndPreserve" });
            }
        },
        
        count: function () {
            try {
                return _handlers.length;
            }
            catch (ex) {
                PeopleMedia.Diagnostics.handleException(ex, { oid: this.Oid, method: "count" });
            }
        }
    };
};

PeopleMedia.ServiceProxy = function (baseUrl) {
    var _baseUrl;
    var _methodName;

    if (baseUrl) {
        _baseUrl = baseUrl;
    }
    return {
        invoke: function (opts) {
            var verb = (opts.verb) ? opts.verb : "GET";
            var dataType = (opts.dataType) ? opts.dataType : "json";
            var proxyUrl = (dataType.toLowerCase() == 'json') ? _baseUrl + '/' + opts.method : _baseUrl + '/' + opts.method + '/' + dataType;

            // use jsonp if being hosted through another domain (e.g. the main site)
            if (document.domain.toLowerCase() != PeopleMedia.Application.ApplicationDomain.toLowerCase()) {
                proxyUrl += "?callbackmethod=?";
            }

            var async = ('async' in opts) ? opts.async : true;
            var timeout = ('timeout' in opts) ? opts.timeout : 60000;
            var startTime = new Date().getTime();
            jQuery.ajax({
                type: verb,
                url: proxyUrl,
                data: opts.data,
                dataType: dataType,
                success: function (response) {
                    if (opts.success) {
                        opts.success(response);
                    }
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    var endTime = new Date().getTime();
                    var duration = (endTime - startTime);
                    var data = PeopleMedia.CP.convertAjaxErrorToFault(jqXHR, textStatus, errorThrown);
                    if (!data.IsCancelled) {
                        PeopleMedia.CP.logAjaxError("Ajax request failure", proxyUrl, { oid: "PeopleMedia.ServiceProxy", method: "invoke", duration: duration }, jqXHR, textStatus, errorThrown, function (jqXHR, textStatus) {
                        });
                    }
                    if (opts.error) {
                        opts.error(jqXHR, textStatus, errorThrown);
                    }
                },
                complete: function (jqXHR, textStatus) {
                    if (opts.complete) {
                        opts.complete(jqXHR, textStatus);
                    }
                },
                async: async,
                timeout: timeout
            });
        }
    };
};

PeopleMedia.UI = {
    Oid: "PeopleMedia.UI",
    busy: function () {
        try {
            $jq('BODY').addClass('ui_busy');
        }
        catch (ex) {
            PeopleMedia.Diagnostics.handleException(ex, { oid:this.Oid, method:"busy" });
        }
    },

    done: function () {
        try {
            $jq('BODY').removeClass('ui_busy');
        }
        catch (ex) {
            PeopleMedia.Diagnostics.handleException(ex, { oid:this.Oid, method:"done" });
        }
    },

    loadDDL: function (ddlId, data, valuePropertyName, textPropertyName) {
        try {
            var ddl = document.getElementById(ddlId);
            $jq.each(data, function (idx, item) {
                try {
                    var o = document.createElement("option");
                    o.text = item[textPropertyName];
                    o.value = item[valuePropertyName];
                    try {
                        ddl.add(o, null);
                    } catch (ex) { // ie only
                        ddl.add(o);
                    }
                }
                catch (ex) {
                    PeopleMedia.Diagnostics.handleException(ex, { oid:this.Oid, method:"loadDDL each" });
                }
            });
        }
        catch (ex) {
            PeopleMedia.Diagnostics.handleException(ex, { oid: this.Oid, method:"loadDDL" });
        }
    },
    loadAgeDropDownList: function (name) {
        try {
            if ($jq('#' + name)) {
                var dropDown = $jq('#' + name);
                var selected = $jq('#' + name).val();
                dropDown.empty();
                for (var i = 18; i <= 120; i++) {
                    dropDown.append("<option value='" + i + "'>" + i + "</option>");
                }
                $jq('#' + name).val(selected);
            }
        }
        catch (ex) {
            PeopleMedia.Diagnostics.handleException(ex, { oid:this.Oid, method:"loadAgeDropDownList" });
        }
    },
    addBookmark: function () {
        try {
            if (window.sidebar) { // FF
                window.sidebar.addPanel(bookmarkTitle, bookmarkUrl, "");
                return;
            } else if (document.all) { // IE
                try {
                    window.external.AddFavorite(bookmarkUrl, bookmarkTitle);
                }
                catch (Error) {
                    alert('Please press CTRL-D to bookmark this page');
                }
                return;
            } else if (window.opera && window.print) {
                alert('Please press CTRL-D to bookmark this page');
                return;
            } else {
                var chr = 'CTRL-D';
                var agt = navigator.userAgent.toLowerCase();
                if (agt.indexOf("opera") != -1) {
                    chr = 'CTRL-T';
                }
                alert('Please press ' + chr + ' to bookmark this page');
                return;
            }
        }
        catch (ex) {
            PeopleMedia.Diagnostics.handleException(ex, { oid:this.Oid, method:"addBookmark" });
        }
    }
};

PeopleMedia.UI.PopupWindow = function () {
    var _container;
    var _dimensions = { height: 220, width: 400 };
    var _position = { left: 0, top: 0 };
    var _url = 'about:blank';
    var _win;

    var self = {
        Oid: "PeopleMedia.UI.PopupWindow",
        init: function (opts) {
            try {
                if (opts != undefined && opts.container != undefined) {
                    _container = opts.container;

                    if (opts.meta != undefined) {
                        if (opts.meta.url != undefined) {
                            _url = opts.meta.url;
                        }
                        if (opts.meta.height != undefined) {
                            _dimensions.height = parseInt(opts.meta.height, 10);
                        }
                        if (opts.meta.width != undefined) {
                            _dimensions.width = parseInt(opts.meta.width, 10);
                        }
                        if (opts.meta.top != undefined) {
                            _position.top = parseInt(opts.meta.top, 10);
                        }
                        if (opts.meta.left != undefined) {
                            _position.left = parseInt(opts.meta.left, 10);
                        }
                        if (opts.meta.timeout != undefined) {
                            setTimeout(
                                function () {
                                    self.show();
                                },
                                opts.meta.timeout
                            );
                        }
                    }
                }
            }
            catch (ex) {
                PeopleMedia.Diagnostics.handleException(ex, { oid:this.Oid, method:"init" });
            }
        },

        show: function () {
            try {
                _win = window.open(_url, "popupWindow", 'toolbar=0,titlebar=0,scrollbars=0,resizable=0,menubar=0,Height=' + _dimensions.height.toString() + ',Width=' + _dimensions.width.toString() + ',top=' + _position.top + ',left=' + _position.left);
                if (_win) {
                    if (_win.focus) {
                        _win.focus();
                    }
                }
            }
            catch (ex) {
                PeopleMedia.Diagnostics.handleException(ex, { oid:this.Oid, method:"show" });
            }
        },

        dismiss: function () {
            try {
                _win.close();
           }
           catch (ex) {
               PeopleMedia.Diagnostics.handleException(ex, { oid:this.Oid, method:"dismiss" });
           }
        }
    };

    return self;
};

PeopleMedia.Types.Byte = function(raw) {
    var _raw = raw;
    var self = {
        isValid: function() {
            if (_raw) {
                if ((_raw - 0) == _raw) {
                    var converted = parseInt(_raw, 10);
                    return converted >= 0 && converted <= 255;
                }
            }
            return false;
        },

        value: function() {
            if (self.isValid()) {
                return parseInt(_raw, 10);
            } else {
                return null;
            }
        },

        getValueOrDefault: function(defaultVal) {
            if (self.isValid()) {
                return self.value();
            } else {
                return defaultVal;
            }
        }
    };

    return self;
};

PeopleMedia.Net = {
    Oid: "PeopleMedia.Net",
    createCookie: function (name, value, days, isArray) {
        var cookieDomain = null;
        try {
            var expires = "";
            cookieDomain = (PeopleMedia.Net.getDomainName(PeopleMedia.CP.DomainName()) || "").toLowerCase();
            if (days) {
                var date = new Date();
                date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                expires = "; expires=" + date.toGMTString();
            }
            if (arguments.length > 3 && isArray) {
                value = PeopleMedia.Net.serializeKeyValues(value);
            }
            document.cookie = name + "=" + value + expires + "; path=/; domain=" + cookieDomain;
        }
        catch (ex) {
            PeopleMedia.Diagnostics.handleException(ex, { oid: this.Oid, method: "createCookie", cookieDomain: cookieDomain });
        }
    },
    getDomainName: function (hostname) {
        var host;
        try {
            host = hostname || window.location.hostname;
            var arr = host.split('.');
            var arrLen = arr.length;
            if (arrLen === 3) {
                return arr[1] + '.' + arr[2];
            }
            if (arrLen === 4) {
                var ip = /^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/g;
                if (ip.test(host)) {
                    return host;
                }
            }
            if (arrLen > 3) {
                return arr[arrLen-2] + '.' + arr[arrLen-1];
            }
        }
        catch (ex) {
            PeopleMedia.Diagnostics.handleException(ex, { oid: this.Oid, method: "getDomainName" });
        }
        return host;
    },
    readCookie: function (name) {
        try {
            var nameEQ = name + "=";
            var ca = document.cookie.split(';');
            for (var i = 0; i < ca.length; i++) {
                var c = ca[i];
                while (c.charAt(0) == ' ') {
                    c = c.substring(1, c.length);
                }
                if (c.indexOf(nameEQ) == 0) {
                    var val = c.substring(nameEQ.length, c.length);
                    if (val.indexOf('&') >= 0) {
                        return PeopleMedia.Net.parseKeyValueString(val);
                    } else {
                        return val;
                    }
                }
            }
        }
        catch (ex) {
            PeopleMedia.Diagnostics.handleException(ex, { oid: this.Oid, method: "readCookie" });
        }
        return null;
    },
    eraseCookie: function (name) {
        try {
            PeopleMedia.Net.createCookie(name, "", -1);
        }
        catch (ex) {
            PeopleMedia.Diagnostics.handleException(ex, { oid: this.Oid, method: "eraseCookie" });
        }
    },
    parseKeyValueString: function (val) {
        var hash = [];
        try {
            var pieces = val.split('&');
            for (var i = 0; i < pieces.length; i++) {
                var pair = pieces[i].split('=');
                hash[pair[0]] = pair[1];
            }
        }
        catch (ex) {
            PeopleMedia.Diagnostics.handleException(ex, { oid: this.Oid, method: "parseKeyValueString" });
        }
        return hash;
    },
    serializeKeyValues: function (hash) {
        try {
            if (hash != null) {
                var pairs = [];
                for (var key in hash) {
                    pairs.push(key + '=' + hash[key]);
                }
                return pairs.join('&');
            }
        }
        catch (ex) {
            PeopleMedia.Diagnostics.handleException(ex, { oid:this.Oid, method:"serializeKeyValues" });
        }
        return null;
    },
    getQueryString: function(queryString) {
        try {
            var qs = (typeof (queryString) === 'undefined' || queryString === null) ? window.location.search : queryString;
            return PeopleMedia.Net.parseQueryString(qs);
        }
        catch (ex) {
            PeopleMedia.Diagnostics.handleException(ex, { oid:this.Oid, method:"getQueryString" });
            return [];
        }
    },
    parseQueryString: function (queryString) {
        try {
            var keyVals = [];
            var raw;
            if (typeof (queryString) === 'undefined' || queryString === null || queryString.length < 1) {
                raw = '';
            } else if (queryString.substring(0, 1) === '?') {
                raw = queryString.substring(1);
            } else {
                raw = queryString;
            }
            var pairs = raw.split("&");
            for (var i = 0, count = pairs.length; i < count; i++) {
                var key = "";
                var val = "";
                var equalPos = pairs[i].indexOf("=");

                if (equalPos < 0) {
                    key = pairs[i];
                    val = null;
                } else {
                    if (equalPos >= 1) {
                        key = pairs[i].substring(0, equalPos);
                    }
                    if (equalPos < pairs[i].length - 1) {
                        val = pairs[i].substring(equalPos + 1, pairs[i].length);
                    }
                }
                if (key.length > 0) {
                    keyVals.push({ "key": key, "value": val });
                }
            }
            return keyVals;
        }
        catch (ex) {
            PeopleMedia.Diagnostics.handleException(ex, { oid:this.Oid, method:"parseQueryString" });
            return [];
        }
    },
    createQueryString: function (keyValues, excludeKeys) {
        try {
            var newQS = "";
            var keyFound;
            var currentKeyValuePair;
            var currentKey;
            var currentKeyLower;
            var currentValue;
            if (typeof (excludeKeys) === 'undefined' || excludeKeys === null || excludeKeys.length <= 0) {
                excludeKeys = [];
            }
            var isArray = (Array.isArray) ? Array.isArray(keyValues) : Object.prototype.toString.call(keyValues) === '[object Array]';
            if (isArray) {
                for (var i = 0, count = keyValues.length; i < count; i++) {
                    currentKeyValuePair = keyValues[i];
                    if (typeof (currentKeyValuePair) !== 'undefined' && currentKeyValuePair !== null && currentKeyValuePair.hasOwnProperty("key") && currentKeyValuePair.hasOwnProperty("value")) {
                        currentKey = currentKeyValuePair["key"];
                        currentKeyLower = (typeof (currentKey) !== 'undefined' && currentKey !== null) ? currentKey.toLowerCase() : currentKey;
                        currentValue = currentKeyValuePair["value"];
                        keyFound = false;
                        for (var excludeIndex = 0, excludeCount = excludeKeys.length; excludeIndex < excludeCount; excludeIndex++) {
                            if (excludeKeys[excludeIndex] && excludeKeys[excludeIndex].toLowerCase() == currentKeyLower) {
                                keyFound = true;
                                break;
                            }
                        }
                        if (!keyFound) {
                            if (newQS.length > 0) {
                                newQS += "&";
                            }
                            newQS += currentKey + ((typeof (currentValue) !== 'undefined' && currentValue !== null) ? ("=" + currentValue) : '');
                        }
                    }
                }
            }
            if (newQS.length > 0) {
                newQS = "?" + newQS;
            }
            return newQS;
        }
        catch (ex) {
            PeopleMedia.Diagnostics.handleException(ex, { oid:this.Oid, method:"createQueryString" });
            return [];
        }
    },
    getQueryStringValue: function (keyValues, key) {
        try {
            var currentKeyValuePair;
            var currentKey;
            var currentKeyLower;
            var keyLower;
            if (typeof (keyValues) !== 'undefined' && keyValues != null && typeof (key) !== 'undefined' && key != null) {
                var isArray = (Array.isArray) ? Array.isArray(keyValues) : Object.prototype.toString.call(keyValues) === '[object Array]';
                if (isArray) {
                    keyLower = key.toLowerCase();
                    for (var i = 0, count = keyValues.length; i < count; i++) {
                        currentKeyValuePair = keyValues[i];
                        if (typeof (currentKeyValuePair) !== 'undefined' && currentKeyValuePair !== null && currentKeyValuePair.hasOwnProperty("key") && currentKeyValuePair.hasOwnProperty("value")) {
                            currentKey = currentKeyValuePair["key"];
                            currentKeyLower = (typeof (currentKey) !== 'undefined' && currentKey !== null) ? currentKey.toLowerCase() : currentKey;
                            if (currentKeyLower == keyLower) {
                                return currentKeyValuePair["value"];
                            }
                        }
                    }
                }
            }
        }
        catch (ex) {
            PeopleMedia.Diagnostics.handleException(ex, { oid:this.Oid, method:"getQueryStringValue" });
        }
        return null;
    },
    createKeyValues: function (dict) {
        try {
            var keyVals = [];
            var val;
            for (var key in dict) {
                if (dict.hasOwnProperty(key) && typeof (key) !== 'undefined' && key !== null && key.length > 0) {
                    val = dict[key];
                    keyVals.push({ "key": key, "value": val });
                }
            }
            return keyVals;
        }
        catch (ex) {
            PeopleMedia.Diagnostics.handleException(ex, { oid: this.Oid, method: "createKeyValues" });
        }
        return [];
    },
    addQueryStringValue: function (url, name, val) {
        try {
            var newUrl = (typeof (url) !== 'undefined' && url !== null) ? url : '';
            var nameValue = ((typeof (name) !== 'undefined' && name !== null) ? name : '') + ((typeof (val) !== 'undefined' && val !== null) ? ("=" + val) : '');
            if (nameValue.length > 0) {
                return newUrl + ((newUrl.indexOf("?") < 0) ? '?' : '&') + nameValue;
            } else {
                return newUrl;
            }
        }
        catch (ex) {
            PeopleMedia.Diagnostics.handleException(ex, { oid:this.Oid, method:"addQueryStringValue" });
            return [];
        }
    },
    getUrlWithoutQueryString: function (url) {
        try {
            if (typeof (url) === 'undefined' || url === null) {
                return '';
            }
            var qIndex = url.indexOf("?");
            if (qIndex < 0) {
                return url;
            } else {
                return url.substring(0, qIndex);
            }
        }
        catch (ex) {
            PeopleMedia.Diagnostics.handleException(ex, { oid: this.Oid, method: "getUrlWithoutQueryString" });
            return [];
        }
    },
    getQueryStringFromUrl: function (url) {
        try {
            if (typeof (url) === 'undefined' || url === null) {
                return '';
            }
            var qIndex = url.indexOf("?");
            if (qIndex > 0) {
                return url.substring(qIndex + 1);
            } else {
                return '';
            }
        }
        catch (ex) {
            PeopleMedia.Diagnostics.handleException(ex, { oid: this.Oid, method: "getQueryStringFromUrl" });
            return [];
        }
    },
    getQueryStringKeys: function (keyValues) {
        var result = [];
        try {
            var currentKeyValuePair;
            var currentKey;
            if (typeof (keyValues) !== 'undefined' && keyValues !== null) {
                var isArray = (Array.isArray) ? Array.isArray(keyValues) : Object.prototype.toString.call(keyValues) === '[object Array]';
                if (isArray) {
                    for (var i = 0, count = keyValues.length; i < count; i++) {
                        currentKeyValuePair = keyValues[i];
                        if (typeof (currentKeyValuePair) !== 'undefined' && currentKeyValuePair !== null && currentKeyValuePair.hasOwnProperty("key") && currentKeyValuePair.hasOwnProperty("value")) {
                            currentKey = currentKeyValuePair["key"];
                            if (typeof (currentKey) !== 'undefined' && currentKey !== null) {
                                result.push(currentKey);
                            }
                        }
                    }
                }
            }
        }
        catch (ex) {
            PeopleMedia.Diagnostics.handleException(ex, { oid:this.Oid, method: "getQueryStringKeys" });
        }
        return result;
    }
};

//This function replaces the asp.net default button functionality.
$jq(document).ready(function () {
    var btn = $jq('.defaultButton');
    btn.parents('.defaultForm').keypress(function (e) {
        try {
            if (e.which == 13 && e.target.type != 'textarea') {
                btn.each(function (index, element) {
                    try {
                        var visible = true;
                        var b = $jq(element);
                        b.parents(':hidden').each(function (index, parent) {
                            visible = false;
                        });
                        if (visible)
                            b.trigger('click');
                    }
                    catch (ex) {
                        PeopleMedia.Diagnostics.handleException(ex, { oid:"lps_core document ready", method:"defaultForm keypress enter" });
                    }
                });
                return false;
            }
        }
        catch (ex) {
            PeopleMedia.Diagnostics.handleException(ex, { oid:"lps_core document ready", method:"defaultForm keypress" });
        }
    });

    try
    {
        PeopleMedia.UI.loadAgeDropDownList('minage');
        PeopleMedia.UI.loadAgeDropDownList('maxage');
    }
    catch (ex) {
        PeopleMedia.Diagnostics.handleException(ex, { oid: "lps_core document ready", method: "loadAgeDropDownList" });
    }
});

(function () {
    if (!window.jQuery) {
       var script = document.createElement('script');
       script.type = "text/javascript";
       script.src = "//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js";
       document.getElementsByTagName('head')[0].appendChild(script);
    }
    var LPS_SET_GENDER_INTERVAL = null;

    var parent = null;
    var removals = null;
    var previousGender = null;

    function LPS_SET_GENDER_DDL() {
        try {
            var gender;

            if(PeopleMedia.CP.GenderSeekEnabled() == true){
                 gender = (jQuery('#ddlProfileResponse_999').val() != null ? Math.floor(jQuery('#ddlProfileResponse_999').val() / 10) : null)  || $jq.queryString.get("iam") ||  PeopleMedia.CP.GenderID();
            }
            else {
                 gender = jQuery('#ddlProfileResponse_13').val() || $jq.queryString.get("iam") ||  PeopleMedia.CP.GenderID();
            }

            if (gender == 0){
                gender = null;
            }

            if (previousGender != gender){
                // Add back in 
                if(removals != null && parent != null){
                    removals.appendTo(parent);
                }

                var selection = $jq('#ddlProfileResponse_4').val();

                if (gender == 2) {
                    removals = jQuery('option:contains("Stocky"),option:contains("Heavyset"), div#divProfileQuestions_6 div#profileresponse_4_6, div#divProfileQuestions_6 div#profileresponse_4_7');
                    parent = jQuery('option:contains("Stocky"),option:contains("Heavyset"), div#divProfileQuestions_6 div#profileresponse_4_6, div#divProfileQuestions_6 div#profileresponse_4_7').parent();
                    //removalCount += removals.length;
                    removals.remove();
                    removals.removeClass('profileresponse_selected');

                    if(selection == 6 || selection == 7){
                        $jq('#ddlProfileResponse_4').val(null);
                    }
                }
                if (gender == 1) {
                    removals = jQuery('option:contains("Big & Beautiful"), div#divProfileQuestions_6 div#profileresponse_4_5');
                    parent = jQuery('option:contains("Big & Beautiful"), div#divProfileQuestions_6 div#profileresponse_4_5').parent();
                    //removalCount += removals.length;
                    removals.remove();
                    removals.removeClass('profileresponse_selected');

                    if(selection == 5){
                        $jq('#ddlProfileResponse_4').val(null);
                    }
                }

                if(removals.length == 0){
                    gender = null;
                }

                previousGender = gender; 
            }
            
        }
        catch (e) {}
    }
    LPS_SET_GENDER_INTERVAL =  setInterval(LPS_SET_GENDER_DDL,500);
})();
